package zzjson.rabbitmq.limit;

import com.rabbitmq.client.*;
import zzjson.rabbitmq.BaseRabbitMq;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.rabbitmq.limit</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月26日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class LimitConsumer2 {
	public static String QUEUE_NAME = "LIMIT_QUEUE";

	public static void main(String[] args) throws IOException {
		Connection conn = BaseRabbitMq.getConn();
		Channel channel = conn.createChannel();

		// 声明队列（默认交换机AMQP default，Direct）
		// String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
		System.out.println("Consumer2 Waiting for message....");

		// 创建消费者，并接收消息
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
									   byte[] body) throws IOException {
				String msg = new String(body, StandardCharsets.UTF_8);
				try {
					TimeUnit.SECONDS.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("Consumer2 Received message : '" + msg + "'" );
				channel.basicAck(envelope.getDeliveryTag(), true);
			}
		};

		//非自动确认消息的前提下，如果一定数目的消息（通过基于consume或者channel设置Qos的值）未被确认前，不进行消费新的消息。
		// 因为Consumer2的处理速率很慢，收到两条消息后都没有发送ACK，队列不会再发送消息给Consumer2
		channel.basicQos(2);
		channel.basicConsume(QUEUE_NAME, false, consumer);

		// BaseRabbitMq.close(channel, conn);

	}
}